import router, { BASIC_ROUTES, ASYNC_ROUTES } from '@/router'
import { appStore } from '@/stores/app'
import { userStore } from '@/stores/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const WHITE_LIST: string[] = [
  '/',
  '/login',
  '/about',
  '/news',
  '/case'
]

BASIC_ROUTES.map(item => {
  // WHITE_LIST.push(item.path) 
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const app = appStore()
  const user = userStore()
  document.title = to.meta?.title as string
  if (user.token) {
    // 已登录
    if (to.path === '/login') {
      next('/')
    } else {
      if (app.filterAsyncRoutes?.length) {
        next()
      } else {
        // 路由鉴权
        app.setFilterAsyncRoutes(ASYNC_ROUTES)
        next({
          ...to,
          replace: true
        })
      }
    }
  } else {
    // 未登录
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next(`/login`)
    }
  }
})

// 路由进入后拦截
router.afterEach(() => {
  NProgress.done()
})